package com.my.ruyi.ssl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.TrustManagerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

public class SslClient {
	static final String HOST = System.getProperty("host", "127.0.0.1");
	static final int PORT = Integer.valueOf(System.getProperty("port", "9998"));
	
	public static void main(String[] args) throws Exception {
		// 创建SSL
//		final SslContext sslContext = SslContextBuilder.forClient()
//				.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		
		NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		TrustManagerFactory trustManagerFactory = null;
		
		try {
			Bootstrap bootstrap = new Bootstrap();
			
			KeyStore keyStore = KeyStore.getInstance("JKS");
			keyStore.load(new FileInputStream("src/main/resources/clientChat.jks"), "c654321".toCharArray());
			trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			trustManagerFactory.init(keyStore);
			
			
			SslContext sslContext = SslContextBuilder.forClient().trustManager(trustManagerFactory).build();
			
			bootstrap.group(eventLoopGroup)
				.channel(NioSocketChannel.class)
				.handler(new SslClientInitializer(sslContext));
			
			Channel channel = bootstrap.connect(HOST, PORT).sync().channel();
			
			ChannelFuture future = null;
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			
			for(;;) {
				String line = reader.readLine();
				if (line == null) {
                    break;
                }
				
				System.out.println("输入的内容：" + line);
				future = channel.writeAndFlush(line + "\r\n");
				if ("bye".equals(line.toLowerCase())) {
					channel.closeFuture().sync();
					break;
				}
			}
			
			// Wait until all messages are flushed before closing the channel.
            if (future != null) {
            	future.sync();
            }
            
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			// The connection is closed automatically on shutdown.
			eventLoopGroup.shutdownGracefully();
		}
	}
}
